package com.wx.disparent.mallparent.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wx.disparent.mallparent.commons.util.PageResult;
import com.wx.disparent.mallparent.entity.MerchantEntity;
import com.wx.disparent.mallparent.entity.ProductEntity;
import com.wx.disparent.mallparent.service.MerchantService;
import com.wx.disparent.mallparent.service.ProductService;
import org.apache.commons.io.FileUtils;
import org.apache.ibatis.reflection.wrapper.ObjectWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 刘杰龙
 * @version 1.0
 * @description 商品控制层
 * @date 2019/12/10 10:28
 */
@RestController
@RequestMapping("/admin/product")
public class ProductControllerForPC {
    /**
     * 文件上传路径
     */
    @Value("${file-location}")
    private String filePath;
    /**
     * 保存文件夹名
     */
    @Value("${file-path-pattern}")
    private String fileDirectory;

    /**
     * 商品服务
     */
    @Autowired
    private ProductService productService;
    /**
     * 商家服务
     */
    @Autowired
    private MerchantService merchantService;

    /**
     * 获取所有商品信息
     *
     * @return 商品集合
     */
    @RequestMapping("/getList")
    public ModelAndView getList() {
        ModelAndView model = new ModelAndView();
        List<ProductEntity> entities = productService.findAll(null);
        model.addObject("products", entities);
        model.setViewName("web/pc/goodsListPage");
        return model;
    }

    /**
     * 获取所有商品信息
     *
     * @return 商品集合
     */
    @RequestMapping("/pageList")
    public ModelAndView pageList(HttpServletRequest request) {
        ModelAndView model = new ModelAndView();
        model.setViewName("web/pc/goodsListPage");
        return model;
    }

    /**
     * 获取所有商品信息 （分页查询）
     *
     * @return 商品集合
     */
    @RequestMapping("/pageTable")
    public String pageTable(@RequestParam("aoData") String aoData) {
        PageResult pr = new PageResult(aoData);
        pr.setOrderBy("id");
        String search = pr.getSearch();

        JSONArray jsonArray = new JSONArray();

        // 从数据库查询，这里返回的的allUser就已经分页成功了
        List<ProductEntity> entities;
        if (search.equals("")) {
            entities = productService.findAll(null);
        } else {
            Map<String, Object> map = new HashMap<>();
            map.put("name", search);
            entities = productService.findAll(map);
        }

        PageInfo<ProductEntity> page = new PageInfo<>(entities);

        for (Object obj : entities) {
            ProductEntity entity = (ProductEntity) obj;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("productID", entity.getId());
            jsonObject.put("productName", entity.getName());
            jsonObject.put("productStatus", entity.getIsEffect());
            jsonObject.put("productOperate", entity.getIsEffect());
            jsonArray.add(jsonObject);
        }

        String json = "{\"sEcho\":" + (pr.getsEcho()+1) + ",\"iTotalRecords\":" + page.getTotal() + ",\"iTotalDisplayRecords\":" + page.getTotal() + ",\"aaData\":" + jsonArray.toString() + "}";

        return json;
    }

    /**
     * 修改商品状态（上架、下架）
     *
     * @param productId 商品ID
     * @param type      要修改的类型：0.上架 1.下架
     * @return 商品集合列表（更改后）
     */
    @RequestMapping("/sellOrSold")
    public ModelAndView sellOrSold(@RequestParam(value = "id") String productId, @RequestParam(value = "type") String type) {
        if (type.equals("0")) {
            productService.changeStatus(Integer.valueOf(productId), "sell");
        } else if (type.equals("1")) {
            productService.changeStatus(Integer.valueOf(productId), "sold");
        }

        return getList();
    }

    /**
     * 修改或添加商品信息
     *
     * @param productId 商品ID
     * @return 商品信息页面
     */
    @RequestMapping("/goodsInfo")
    public ModelAndView goodsInfo(@RequestParam(value = "id", required = false) Integer productId) {
        ModelAndView model = new ModelAndView();

        Map<String, Object> param = new HashMap<String,Object>();
        param.put("isDel","0");
        ProductEntity productEntity = null;
        if (productId != null && !productId.equals("")) {
            productEntity = productService.findById(productId);
            Integer businessId = productEntity.getBusinessId();
            MerchantEntity merchantEntity = merchantService.findById(businessId);
            model.addObject("merchant", merchantEntity);
        } else {
            List<MerchantEntity> userEntities = merchantService.findAll(param);
            model.addObject("merchants", userEntities);
        }

        model.addObject("product", productEntity);
//            model.addObject("userEntity",productEntity);
        model.setViewName("web/pc/goodsInformationPage");
        return model;
    }

    /**
     * fileinput图片上传
     *
     * @param file 要上传的文件
     * @param req  请求
     * @return 商品信息
     */
    @RequestMapping("/uploadImage")
    public Map<String, String> uploadImage(@RequestParam("images") MultipartFile file, HttpServletRequest req) {
        Map<String, String> map = null;

        if (file.isEmpty()) {
            return map;
        } else {
            map = new HashMap<>();
            String fileName = file.getOriginalFilename();

            File localFile = new File(filePath + fileDirectory);
            if (!localFile.exists()) {
                localFile.mkdirs();
            }
            // 获取文件的后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            //获取当前时间
            String time = String.valueOf(System.currentTimeMillis());
            //文件重命名，实际处理肯定是要加上一段唯一的字符串（如现在时间），这里简单加 cun
            String newFileName = time + suffixName;
            String path = filePath + fileDirectory + "/" + newFileName;
            try {
                File server_file = new File(path);
                file.transferTo(server_file);
            } catch (Exception e) {
                e.printStackTrace();
            }

            map.put("fileName", fileName);
            map.put("fileSize", String.valueOf(file.getSize()));
            map.put("url", req.getServletContext().getContextPath() + "/upload/" + newFileName);

            return map;
        }
    }

    /**
     * fileinput删除单张图片
     *
     * @param id      要删除的文件
     * @param imgName 请求
     * @return 商品信息
     */
    @RequestMapping("/delImage")
    public Map<String, String> delImage(@RequestParam("id") Integer id, @RequestParam("imgName") String imgName, HttpServletRequest req) {
        Map<String, String> map = new HashMap<>();

        String image = imgName.substring(1);
        File file = new File(filePath + image);
        if (file.exists()) {
            file.delete();
        }

        ProductEntity productEntity = productService.findById(id);
        String oldImage = productEntity.getImage();

        List preview = new ArrayList();
        List config = new ArrayList();

        StringBuilder sb = new StringBuilder();

        if (oldImage.indexOf(";") > 0) {
            String[] strs = oldImage.split(";");
            for (int i = 0; i < strs.length; i++) {
                if (strs[i].equals(imgName)) {
                    continue;
                }
//            preview.add("<img src='"+strs[i]+"' width='500' class='file-preview-image kv-preview-data rotate-38827 is-portrait-gt4' alt='' title='#' style=' height: auto; max-width: 100%; max-height: 100%; margin-top: 0px;'>");
//            preview.add("'"+strs[i]+"'");
                preview.add(strs[i]);
                config.add("{'caption': \"商品图片\",'key':'" + i + "','url':\"/admin/product/delImage?id=" + id + "&imgName=" + strs[i] + "\"}");

                if (sb.length() > 0) {
                    sb.append(";" + strs[i]);
                } else {
                    sb.append(strs[i]);
                }
            }
        }

        String newImage = sb.toString();

        productEntity.setImage(newImage);

        productService.update(productEntity);

        /*sb = new StringBuilder("{initialPreview: ");
        sb.append(preview.toString());
        sb.append(",initialPreviewConfig: ");
        sb.append(config.toString());
        sb.append("}");*/

        map.put("initialPreview", preview.toString());
        map.put("initialPreviewConfig", config.toString());
        return map;
    }

    /**
     * 富文本图片上传
     *
     * @param file 要上传的文件
     * @param req  请求
     * @return 商品信息
     */
    @RequestMapping("/ckEditorUpload")
    public Map<String, Object> ckEditorUpload(@RequestParam("upload") MultipartFile file, HttpServletRequest req, HttpServletResponse rsp) throws Exception {
        Map<String, Object> map = new HashMap<>();

        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //获取当前时间
        String time = String.valueOf(System.currentTimeMillis());
        //文件重命名，实际处理肯定是要加上一段唯一的字符串（如现在时间），这里简单加 cun
        String newFileName = time + suffixName;
        //图片路径
        String url = filePath + fileDirectory + "/" + newFileName;

        //使用架包 common-io实现图片上传
        FileUtils.copyInputStreamToFile(file.getInputStream(), new File(url));


        map.put("uploaded", 1);
        map.put("fileName", fileName);
        map.put("url", req.getServletContext().getContextPath() + "/upload/" + newFileName);

        return map;
    }

    /**
     * 添加或修改商品
     *
     * @param productEntity 商品对象
     * @return 商品信息
     */
    @RequestMapping("/addOrModify")
    public ModelAndView saveProduct(ProductEntity productEntity) {
        if (productEntity.getId() != null) {
            ProductEntity productTemp = productService.findById(productEntity.getId());

            productEntity.setBusinessId(productTemp.getBusinessId());
            productEntity.setIsEffect(productTemp.getIsEffect());
            productService.update(productEntity);
        } else {
            productService.insert(productEntity);
        }

        return getList();
    }
}
